package com.budwk.app.sqfwV2.component;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.sqfw.constants.DictConstants;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfwV2.constants.ProblemConstant;
import com.budwk.app.sqfwV2.dto.dto.centuryCity.SafeCheckTaskParamDataDTO;
import com.budwk.app.sqfwV2.dto.dto.centuryCity.SafeCheckTaskPdfDTO;
import com.budwk.app.sqfwV2.dto.entity.SqfwProblemInfo;
import com.budwk.app.sqfwV2.enums.BinYangFileServiceEnum;
import com.budwk.app.sqfwV2.enums.RectificateTimeEnum;
import com.budwk.app.sqfwV2.enums.centuryCitySafe.CampusTrainingProblemsEnum;
import com.budwk.app.sqfwV2.enums.centuryCitySafe.EnterpriseSafetyProblemsEnum;
import com.budwk.app.sqfwV2.enums.centuryCitySafe.LargeSafeProblemsEnum;
import com.budwk.app.sqfwV2.generator.binyangStreet.excel.BinyangStreetExcelGenerator;
import com.budwk.app.sqfwV2.service.ProblemInfoService;
import com.budwk.app.sys.models.Sys_dict;
import com.budwk.app.sys.services.SysDictService;
import com.budwk.app.util.StrUtil;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.ioc.loader.annotation.IocBean;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 宾阳街道业务代码公共类
 */

@IocBean
@Slf4j
public class BinyangStreetComponent {

    // 判断是否是宾阳街道的操作人
    public static boolean isBinYangCity(String district, String county) {
        // 宾阳街道和观山街道走同一套逻辑代码
        List<String> codes = List.of(DictConstants.BINYANG_SAFE_CODE, DictConstants.GUANSHAN_SAFE_CODE);
        SysDictService dictService = NutzIocUtils.getBean(SysDictService.class);
        List<Sys_dict> sysDicts = dictService.batchQueryByCodes(codes);
        if (sysDicts.size() > 0) {
            return true;
        }
        // 没有获取到，走原有逻辑
        // 判断当前操作人是否为宾阳街道是 必须是观山湖区下的宾阳街道
        List<String> districts = List.of("观山湖区");
        List<String> countys = List.of("宾阳街道", "观山街道");
        // 只处理宾阳街道的数据
        return districts.contains(district) && countys.contains(county);
    }

    public static Sqfw_formSummary_new queryLastData(Sqfw_formSummary_new summaryNew, String type) {
        SqfwFormsummaryNewService formsummaryNewService = NutzIocUtils.getBean(SqfwFormsummaryNewService.class);
        SafeCheckTaskPdfDTO roadPdfDTO = JSONObject.parseObject(summaryNew.getParamData(), SafeCheckTaskPdfDTO.class);
        List<Sqfw_formSummary_new> formSummaryNews = formsummaryNewService.queryByPlaceAndAddress(roadPdfDTO.getPlaceName(),
                roadPdfDTO.getAddress(), type, summaryNew.getUnitId());
        if (formSummaryNews.size() == 0) {
            return null;
        }
        List<Sqfw_formSummary_new> results = new ArrayList<>();
        for (Sqfw_formSummary_new formSummaryNew : formSummaryNews) {
            SafeCheckTaskPdfDTO roadPdfDTO1 = JSONObject.parseObject(formSummaryNew.getParamData(), SafeCheckTaskPdfDTO.class);
            if (roadPdfDTO.getType().equals(roadPdfDTO1.getType())) {
                results.add(formSummaryNew);
            }
        }
        // 取出小于当前提交时间的所有数据
        List<Sqfw_formSummary_new> formSummaryData = results.stream().filter(e -> e.getCreateDate().getTime() < summaryNew.getCreateDate().getTime()).collect(Collectors.toList());
        if (formSummaryData.size() > 0) {
            return formSummaryData.get(0);
        }
        return null;
    }

    // 处理提交前的数据
    public static void handleBeforeSubmitParam(Sqfw_formSummary_new formSummary) {
        // 1 区县为直属或者观山湖区  社区为直属或者宾阳街道
        // 这些街道可以用同一套模板解析
        if (!isBinYangCity(formSummary.getDistrict(), formSummary.getCounty())) {
            return;
        }
        SafeCheckTaskPdfDTO pdfDTO = JSONObject.toJavaObject(JSONObject.parseObject(formSummary.getParamData()), SafeCheckTaskPdfDTO.class);
        // 获取上一条数据
        Sqfw_formSummary_new lastData = queryLastData(formSummary, SupportBusinessTypeEnum.SAFE_CHECK.getName());
        if (lastData != null) {
            pdfDTO.setLastSummaryId(lastData.getId());
        }
        BinYangFileServiceEnum serviceEnum = BinYangFileServiceEnum.getByLabel(pdfDTO.getType(), formSummary.getDistrict(), formSummary.getCounty());
        if (serviceEnum == null) {
            return;
        }
        // 2 大型企业数据处理
        if (BinYangFileServiceEnum.ONE_PDF.getLabel().equals(pdfDTO.getType())) {
            handleLargeCompany(formSummary, pdfDTO);
            pdfDTO.setExtraProblemVo(ProblemComponent.getExtraProblemVo(LargeSafeProblemsEnum.getDefaultValues(), pdfDTO.getHiddenDanger()));
        }
        // 3 企业安全生产主体
        if (BinYangFileServiceEnum.TWO_PDF.getLabel().equals(pdfDTO.getType())) {
            handleEnterpriseSafety(formSummary, pdfDTO);
            pdfDTO.setExtraProblemVo(ProblemComponent.getExtraProblemVo(EnterpriseSafetyProblemsEnum.getDefaultValues(), pdfDTO.getHiddenDanger()));
        }
        // 4 校外培训机构
        if (BinYangFileServiceEnum.THREE_PDF.getLabel().equals(pdfDTO.getType())) {
            campusTrainingProblems(formSummary, pdfDTO);
            pdfDTO.setExtraProblemVo(ProblemComponent.getExtraProblemVo(CampusTrainingProblemsEnum.getDefaultValues(), pdfDTO.getHiddenDanger()));
        }
        // 5 物流仓储
        if (BinYangFileServiceEnum.FORE_PDF.getLabel().equals(pdfDTO.getType())) {
            // 如果所有问题为空
            ProblemInfoService problemInfoService = NutzIocUtils.getBean(ProblemInfoService.class);
            List<SqfwProblemInfo> problemInfos = problemInfoService.findByCode(ProblemConstant.BINGYANG_LOGISTICS_PROBLEM_CODE);
            initProblems(problemInfos, formSummary, pdfDTO);
            pdfDTO.setExtraProblemVo(ProblemComponent.getExtraProblemVo(getDefaultValues(problemInfos), pdfDTO.getHiddenDanger()));
        }

        SafeCheckTaskPdfDTO f = StrUtil.serializerData(SafeCheckTaskPdfDTO.class, pdfDTO);
        formSummary.setParamData(JSONObject.toJSONString(f));
    }

    /**
     * 获取所有问题的默认值
     * @return
     */
    public static List<SafeCheckTaskParamDataDTO> getDefaultValues(List<SqfwProblemInfo> problemInfos) {
        List<SafeCheckTaskParamDataDTO> list = new ArrayList<>();
        for (SqfwProblemInfo p : problemInfos) {
            SafeCheckTaskParamDataDTO s = new SafeCheckTaskParamDataDTO();
            s.setKey(p.getDefaultValue()).setFields(p.getFields()).setRiskCode(String.valueOf(p.getRiskCode())).setRiskDesc(p.getRiskDesc());
            list.add(s);
        }
        return list;
    }

    private static void initProblems(List<SqfwProblemInfo> problemInfos, Sqfw_formSummary_new formSummary, SafeCheckTaskPdfDTO pdfDTO) {
        List<SafeCheckTaskParamDataDTO> hiddenDanger = pdfDTO.getHiddenDanger();
        // 初始化默认值
        List<SafeCheckTaskParamDataDTO> defaultValues = getDefaultValues(problemInfos);
        if (hiddenDanger == null) {
            pdfDTO.setHiddenDanger(defaultValues);
            return;
        }
        for (SafeCheckTaskParamDataDTO defaultValue : defaultValues) {
            Optional<SqfwProblemInfo> optional = problemInfos.stream().filter(e -> e.getFields().equals(defaultValue.getFields())).findFirst();
            if (optional.isPresent()) {
                SqfwProblemInfo problemInfo = optional.get();
                boolean isExistHidder = initProblemParam(defaultValue, hiddenDanger, problemInfo.getHarardDesc());
                if (isExistHidder) {
                    formSummary.setIssueStatus("1");
                }
            }
        }
    }

    private static void handleLargeCompany(Sqfw_formSummary_new formSummary, SafeCheckTaskPdfDTO pdfDTO) {
        List<SafeCheckTaskParamDataDTO> hiddenDanger = pdfDTO.getHiddenDanger();
        // 如果所有问题为空
        List<SafeCheckTaskParamDataDTO> defaultValues = LargeSafeProblemsEnum.getDefaultValues();
        if (hiddenDanger == null) {
            pdfDTO.setHiddenDanger(defaultValues);
            return;
        }
        for (SafeCheckTaskParamDataDTO defaultValue : defaultValues) {
            LargeSafeProblemsEnum problemsEnum = LargeSafeProblemsEnum.getEnumByFields(defaultValue.getFields());
            boolean isExistHidder = initProblemParam(defaultValue, hiddenDanger, problemsEnum.getHarardDesc());
            if (isExistHidder) {
                if (!defaultValue.getFields().equals(LargeSafeProblemsEnum.FIVE.getFields())) {
                    formSummary.setIssueStatus("1");
                }
            }
        }
    }

    private static void campusTrainingProblems(Sqfw_formSummary_new formSummary, SafeCheckTaskPdfDTO pdfDTO) {
        List<SafeCheckTaskParamDataDTO> hiddenDanger = pdfDTO.getHiddenDanger();
        // 如果所有问题为空
        List<SafeCheckTaskParamDataDTO> defaultValues = CampusTrainingProblemsEnum.getDefaultValues();
        if (hiddenDanger == null) {
            pdfDTO.setHiddenDanger(defaultValues);
            return;
        }
        for (SafeCheckTaskParamDataDTO defaultValue : defaultValues) {
            CampusTrainingProblemsEnum problemsEnum = CampusTrainingProblemsEnum.getEnumByFields(defaultValue.getFields());
            boolean isExistHidder = initProblemParam(defaultValue, hiddenDanger, problemsEnum.getHarardDesc());
            if (isExistHidder) {
                formSummary.setIssueStatus("1");
            }
        }
    }

    private static void handleEnterpriseSafety(Sqfw_formSummary_new formSummary, SafeCheckTaskPdfDTO pdfDTO) {
        List<SafeCheckTaskParamDataDTO> hiddenDanger = pdfDTO.getHiddenDanger();
        // 如果所有问题为空
        List<SafeCheckTaskParamDataDTO> defaultValues = EnterpriseSafetyProblemsEnum.getDefaultValues();
        if (hiddenDanger == null) {
            pdfDTO.setHiddenDanger(defaultValues);
            return;
        }
        for (SafeCheckTaskParamDataDTO defaultValue : defaultValues) {
            EnterpriseSafetyProblemsEnum problemsEnum = EnterpriseSafetyProblemsEnum.getEnumByFields(defaultValue.getFields());
            boolean isExistHidder = initProblemParam(defaultValue, hiddenDanger, problemsEnum.getHarardDesc());
            if (isExistHidder) {
                formSummary.setIssueStatus("1");
            }
        }
    }

    private static boolean initProblemParam(SafeCheckTaskParamDataDTO defaultValue, List<SafeCheckTaskParamDataDTO> hiddenDanger, String harardDesc) {
        // 判断前端是否传递了该参数
        Optional<SafeCheckTaskParamDataDTO> optional = hiddenDanger.stream().filter(e -> defaultValue.getFields().equals(e.getFields())).findFirst();
        if (optional.isEmpty()) {
            // 前端未传递该参数 给默认值
            hiddenDanger.add(defaultValue);
            return false;
        }
        SafeCheckTaskParamDataDTO safe = optional.get();
        safe.setRiskCode(defaultValue.getRiskCode()).setRiskDesc(defaultValue.getRiskDesc());
        if (safe.getKey().equals(defaultValue.getKey())) {
            return false;
        }
        // 组装隐患级别中文名和整改时限中文名
        String nameByCode = RectificateTimeEnum.getNameByCode(safe.getRectificationTypeCode());
        if (StringUtils.isNotEmpty(nameByCode)) {
            safe.setRectificationType(nameByCode);
        }
        String dictName = DayingRoadPdfComponent.getDictName(safe.getRiskLevelCode(), null);
        if (StringUtils.isNotEmpty(dictName)) {
            safe.setRiskLevel(dictName);
        }
        if (StringUtils.isNotEmpty(harardDesc)) {
            safe.setNineSmallPlacesIssuesAndRisks(harardDesc);
        }
        safe.setReportNineSmallPlaces("已告知");
        return true;
    }

    public static void getCheckDataIndexList(List<String> typeList, List<Sqfw_formSummary_new> sqfwFormSummaryNewList, List<String> indexList) {
        for (String type : typeList) {
            List<BinYangFileServiceEnum> allExcel = BinYangFileServiceEnum.getAllExcel();
            Optional<BinYangFileServiceEnum> optional = allExcel.stream().filter(e -> e.getLabel().equals(type)).findFirst();
            if (optional.isPresent()) {
                BinYangFileServiceEnum serviceEnum = optional.get();
                BinyangStreetExcelGenerator service = (BinyangStreetExcelGenerator) serviceEnum.getService();
                // 检查是否有数据
                List<Sqfw_formSummary_new> exportData = service.getExportData(sqfwFormSummaryNewList);
                if (exportData.size() > 0) {
                    List<String> codeByLabel = BinYangFileServiceEnum.getCodeByLabel(type);
                    indexList.addAll(codeByLabel);
                }
            }
        }
    }

    public static void buildNullMap(List<Map<String, Object>> listMap, SafeCheckTaskPdfDTO roadPdfDTO, Sqfw_formSummary_new summary) {
        Map<String, Object> map = buildBaseExcelMap(roadPdfDTO, summary);
        map.put("riskImagesStr", "无");
        listMap.add(map);
    }


    public static Map<String, Object> buildBaseExcelMap(SafeCheckTaskPdfDTO roadPdfDTO, Sqfw_formSummary_new summary) {
        Map<String, Object> map = new HashMap<>(20);
        map.put("inspectionDate", DateUtil.format(summary.getFillDate(), "yyyy年MM月dd日"));
        map.put("placeName", StrUtil.formatStr(roadPdfDTO.getPlaceName()));
        map.put("address", StrUtil.formatStr(roadPdfDTO.getAddress()));
        String peers = roadPdfDTO.getPeers();
        if (StringUtils.isEmpty(peers)) {
            peers = summary.getCreateUserName();
        }
        map.put("createName", peers);
        map.put("problemDesc", "无"); // 问题隐患
        map.put("riskLevel", "无"); // 隐患级别
        map.put("reportDesc", "无"); // 报告情况
        map.put("disposal", "无"); // 处置情况
        // 整改后图片
        map.put("riskImages", new ArrayList<>());
        map.put("riskImagesStr", "");
        if(cn.hutool.core.util.StrUtil.isEmpty(roadPdfDTO.getPeers())){
            roadPdfDTO.setPeers( summary.getCreateUserName());
        }
        map.put("peers", roadPdfDTO.getPeers());
        // 走访图片
        SignImageComponent.signExcel(map, 6, roadPdfDTO.getVisitPicturesFileList(), "无", "visitPictures", "visitPicturesStr");
        return map;
    }

    /**
     * 判断上一次的数据是否包含期限整改
     * @param lastSummaryId
     * @param defaultValues
     * @return
     */
    public static boolean checkLastExistIsDanger(String lastSummaryId, List<SafeCheckTaskParamDataDTO> defaultValues) {
        SqfwFormsummaryNewService formsummaryNewService = NutzIocUtils.getBean(SqfwFormsummaryNewService.class);
        Sqfw_formSummary_new summaryNew = formsummaryNewService.fetch(lastSummaryId);
        if (summaryNew != null) {
            SafeCheckTaskPdfDTO roadPdfDTO = JSONObject.parseObject(summaryNew.getParamData(), SafeCheckTaskPdfDTO.class);
            List<SafeCheckTaskParamDataDTO> hiddenDanger = roadPdfDTO.getHiddenDanger();
            if (hiddenDanger == null || hiddenDanger.size() == 0) {
                return false;
            }
            for (SafeCheckTaskParamDataDTO safe : hiddenDanger) {
                Optional<SafeCheckTaskParamDataDTO> optional = defaultValues.stream().filter(e -> e.getFields().equals(safe.getFields())).findFirst();
                if (!safe.getKey().equals(optional.get().getKey())) {
                    if (RectificateTimeEnum.isDeadline(safe.getRectificationTypeCode())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public static SafeCheckTaskPdfDTO getNextSafeCheckTaskPdfDTO(String summaryId, List<Sqfw_formSummary_new> lastFormSummary) {
        if (lastFormSummary == null || lastFormSummary.size() == 0) {
            return null;
        }
        for (Sqfw_formSummary_new summary : lastFormSummary) {
            SafeCheckTaskPdfDTO roadPdfDTO = JSONObject.parseObject(summary.getParamData(), SafeCheckTaskPdfDTO.class);
            if (summaryId.equals(roadPdfDTO.getLastSummaryId())) {
                return roadPdfDTO;
            }
        }
        return null;
    }
}
